<script lang="ts" setup>
const props = withDefaults(
  defineProps<{
    autofocus?: boolean;
    checked?: boolean;
    disabled?: boolean;
    id?: string;
    modelValue?: boolean;
    name?: string;
    value?: string;
  }>(),
  {
    autofocus: false,
    checked: false,
    disabled: false,
    modelValue: undefined,
    name: undefined,
    value: '',
    id: undefined,
  },
);
const emit = defineEmits<{
  change: [event: Event];
  input: [event: Event];
  'update:modelValue': [value: boolean];
}>();
// Define slots
defineSlots<{
  'checked-indicator'?: () => any;
  default?: () => any;
}>();
const radioRef = ref<HTMLElement | null>(null);
const internalChecked = ref(props.checked);
// Handle modelValue prop for v-model support
const isControlled = computed(() => props.modelValue !== undefined);
watch(
  () => props.modelValue,
  (value) => {
    if (isControlled.value && value !== internalChecked.value) {
      internalChecked.value = !!value;
    }
  },
);
watch(
  () => props.checked,
  (value) => {
    if (!isControlled.value && value !== internalChecked.value) {
      internalChecked.value = value;
    }
  },
);
// Methods
const updateChecked = (event: Event) => {
  if (isControlled.value) {
    emit('update:modelValue', true);
  } else {
    internalChecked.value = true;
  }
  emit('change', event);
  emit('input', event);
};
// onMounted hook to set autofocus if needed
onMounted(() => {
  if (props.autofocus && radioRef.value) {
    (radioRef.value as HTMLElement).focus();
  }
});
</script>
<template>
  <fluent-radio
    ref="radioRef"
    :checked="isControlled ? modelValue : internalChecked"
    :disabled="disabled"
    :name="name"
    :value="value"
    :id="id"
    @change="updateChecked"
  >
    <slot></slot>
    <!-- eslint-disable-next-line vue/no-deprecated-slot-attribute -->
    <span v-if="$slots['checked-indicator']" slot="checked-indicator">
      <slot name="checked-indicator"></slot>
    </span>
  </fluent-radio>
</template>

<style scoped></style>
